<template>
  <div class="form-single-fragment" style="position: relative;">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="170px" size="mini" label-position="right">
      <el-row :gutter="20" class="form-single-info">
        <el-col :span="24">
          <el-col :span="12">
            <el-form-item label="任务名称" prop="taskName">
              <el-input class="input-item" v-model="ruleForm.taskName" placeholder="请输入" maxlength="20"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联计划" prop="planId">
              <el-select v-model="ruleForm.planId" placeholder="请选择">
                <el-option v-for="item in planDtoList" :key="item.planId"
                :label="item.planName" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行人" prop="executeUserId">
              <el-select v-model="ruleForm.executeUserId" placeholder="请选择">
                <el-option v-for="(item, index) in listUsers" :key="index"
                :label="item.showName" :value="item.userId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="参与人">
              <el-select v-model="ruleForm.userIds" multiple collapse-tags placeholder="请选择">
                <el-option v-for="(item, index) in listUsers" :key="index"
                :label="item.showName" :value="item.userId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审核流程" prop="businessFlowId">
              <el-select v-model="ruleForm.businessFlowId" disabled="true" placeholder="请选择" @change="flowEntryChange">
                <el-option v-for="(item,index) in flowEntrylist" :key="index"
                :label="item.flowName" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设置截至时间" prop="endDate">
              <el-date-picker v-model="ruleForm.endDate" type="date" placeholder="选择日期"
              format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="审核流程进度">
              <ProcessViewer ref="ProcessViewers" :style="{height: (getMainContextHeight - 500) + 'px'}"
                :xml="processXml"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="任务描述">
              <el-input type="textarea" class="input-item" rows="4" v-model="ruleForm.taskDesc" placeholder="请输入" maxlength="20"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="任务日志">
              <el-scrollbar style="height:15vh;">
                <el-timeline>
                  <el-timeline-item
                    v-for="(activity, index) in activities"
                    :key="index"
                    :timestamp="activity.createTime">
                    {{activity.userName}}：{{activity.content}}
                  </el-timeline-item>
                </el-timeline>
              </el-scrollbar>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="ruleForm.assigneeName">
            <el-form-item label="指定审批人">{{ruleForm.assigneeName}}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item style="padding: 20px 0;">
              <el-button @click="onCancel(false)">取消</el-button>
              <el-button type="danger" @click="handleDelete()" v-if="tasksId">删除</el-button>
              <el-button type="primary" @click="submitForm()">确定</el-button>
              <el-button type="primary" @click="submitOver()">提交完成</el-button>
            </el-form-item>
          </el-col>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { Administration, BusinessFlow } from '@/api/projectAdministration.js';
import ProcessViewer from '@/views/workflow/components/ProcessViewer.vue';
import { FlowDesignatedController } from '@/api/flowController.js';
import TaskAssigneeSelect from '@/views/workflow/components/TaskAssigneeSelect.vue';
import { mapGetters } from 'vuex';
import ProjectsTasksComplete from './ProjectsTasksComplete.vue';
export default {
  name: 'ProjectsTasksAdd',
  components: { ProcessViewer },
  props: {
    tasksId: {
      default: undefined
    },
    businessType: {
      default: undefined
    },
    projectId: {
      default: undefined
    }
  },
  data () {
    return {
      loading: false,
      isShowloading: false,
      processXml: undefined,
      listUsers: [],
      flowEntrylist: [],
      planDtoList: [],
      situation: 1,
      activities: [],
      flowEntrys: '',
      ruleForm: {
        taskName: '',
        planId: '',
        executeUserId: '',
        endDate: '',
        userIds: [],
        businessFlowId: '',
        taskDesc: '',
        assignee: '',
        assigneeName: ''
      },
      rules: {
        taskName: [{ required: true, message: '请输入', trigger: 'blur' }],
        planId: [{ required: true, message: '请选择', trigger: 'change' }],
        executeUserId: [{ required: true, message: '请选择', trigger: 'change' }],
        endDate: [{ required: true, message: '请输入', trigger: 'change' }],
        taskDesc: [{ required: true, message: '请输入', trigger: 'blur' }],
        businessFlowId: [{ required: true, message: '请选择', trigger: 'change' }]
      }
    };
  },
  created () {
    this.listGroupUser()
    this.loadflowWidgetData()
  },
  computed: {
    isEdit () {
      return this.tasksId != null && this.tasksId !== '';
    },
    ...mapGetters(['getMainContextHeight'])
  },
  mounted () {
    this.listGroupUser()
    this.loadplanlistWidgetData()
    if (this.isEdit) {
      this.loadWorkflowDetail()
      this.loadTasklogWidgetData()
    }
  },
  methods: {
    /**
     * 任务详情
     */
    loadWorkflowDetail () {
      let params = {
        id: this.tasksId
      }
      return new Promise((resolve, reject) => {
        Administration.taskview(this, params).then(res => {
          this.ruleForm = res.data
          this.processXml = res.data.bpmnXml
          setTimeout(() => {
            this.$nextTick(() => {
              this.$refs.ProcessViewers.processReZoom()
            });
          }, 500)
          this.loadflowWidgetData();
          this.$forceUpdate();
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 任务日志
     */
    loadTasklogWidgetData () {
      let params = {
        taskId: this.tasksId,
        logType: 2
      };
      return new Promise((resolve, reject) => {
        Administration.tasklog(this, params).then(res => {
          this.activities = res.data
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 项目计划
     */
    loadplanlistWidgetData () {
      let params = {
        projectId: this.$route.query.projectId ? this.$route.query.projectId : this.projectId
      };
      return new Promise((resolve, reject) => {
        Administration.planlist(this, params).then(res => {
          this.planDtoList = res.data
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 审核流程列表
     */
    loadflowWidgetData () {
      let params = {
        businessStage: 2,
        businessType: this.$route.query.businessType ? this.$route.query.businessType : this.businessType
      }
      return new Promise((resolve, reject) => {
        BusinessFlow.lists(this, params).then(res => {
          this.flowEntrylist = res.data
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 审核流程选择
     */
    flowEntryChange (value) {
      this.ruleForm.assignee = '';
      this.ruleForm.assigneeName = '';
      this.flowEntrylist.forEach(item => {
        if (item.id === value) {
          this.processXml = item.bpmnXml
          setTimeout(() => {
            this.$nextTick(() => {
              this.$refs.ProcessViewers.processReZoom()
            });
          }, 500)
        }
      })
    },
    /**
     * 人员列表
     */
    listGroupUser () {
      let params = {
        projectId: this.$route.query.projectId ? this.$route.query.projectId : this.projectId
      };
      return new Promise((resolve, reject) => {
        Administration.userall(this, params).then(res => {
          this.listUsers = res.data
        }).catch(e => {
          reject(e);
        });
      });
    },
    saveForm () {
      this.ruleForm.projectId = this.$route.query.projectId ? this.$route.query.projectId : this.projectId
      if (this.isEdit) { // 修改
        let params = {
          updateDto: this.ruleForm
        };
        return new Promise((resolve, reject) => {
          Administration.taskupdate(this, params).then(res => {
            this.$message({
              showClose: true,
              message: '修改成功！',
              type: 'success'
            });
            this.onCancel(true);
          }).catch(e => {
            reject(e);
          });
        });
      } else { // 添加
        let params = {
          addDto: this.ruleForm
        };
        return new Promise((resolve, reject) => {
          Administration.taskadd(this, params).then(res => {
            this.$message({
              showClose: true,
              message: '操作成功！',
              type: 'success'
            });
            this.onCancel(true);
          }).catch(e => {
            reject(e);
          });
        });
      }
    },
    /**
     * 提交表单
     */
    submitForm () {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.saveForm()
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 提交完成
    submitOver () {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          let params = {
            tasksId: this.tasksId,
            businessFlowId: this.ruleForm.businessFlowId
          };
          this.$dialog.show('任务完成', ProjectsTasksComplete, {
            area: '600px'
          }, params).then(res => {
            this.getTaskDesignate(res)
          }).catch(e => {});
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    getTaskDesignate (valueData) {
      let params = {
        businessFlowId: this.ruleForm.businessFlowId
      }
      return new Promise((resolve, reject) => {
        FlowDesignatedController.getTaskDesignateUser(this, params).then(res => {
          if (res.data && (this.ruleForm.assignee === '' || this.ruleForm.assignee === undefined)) {
            this.$dialog.show('选择审批人', TaskAssigneeSelect, {
              area: ['1000px', '600px']
            }, {
              multiple: false,
              userTable: res.data
            }).then(res => {
              let assignee = null;
              let assigneeName = null;
              if (Array.isArray(res)) {
                assignee = res.map(item => item.loginName).join(',');
                assigneeName = res.map(item => item.showName).join(',');
              } else {
                assignee = (res || {}).loginName;
                assigneeName = (res || {}).showName;
              }
              this.ruleForm.assignee = assignee;
              this.ruleForm.assigneeName = assigneeName;
              this.$forceUpdate()
              this.subComplete(valueData)
            }).catch(e => {});
          } else {
            this.subComplete(valueData)
          }
        })
      });
    },
    // 提交完成
    subComplete (data) {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          let params = {
            taskId: this.tasksId,
            flowId: this.ruleForm.businessFlowId,
            assignee: this.ruleForm.assignee,
            ...data
          }
          return new Promise((resolve, reject) => {
            Administration.taskcomplete(this, params).then(res => {
              this.$message.success('提交完成！');
              this.onCancel(true);
            }).catch(e => {
              reject(e);
            });
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // // 提交完成
    // subComplete (data) {
    //   let params = {
    //     taskId: this.tasksId,
    //     flowId: this.ruleForm.businessFlowId,
    //     assignee: this.ruleForm.assignee,
    //     ...data
    //   }
    //   return new Promise((resolve, reject) => {
    //     Administration.taskcomplete(this, params).then(res => {
    //       this.$message.success('提交完成！');
    //       this.onCancel(true);
    //     }).catch(e => {
    //       reject(e);
    //     });
    //   });
    // },
    // 删除
    handleDelete () {
      this.$confirm('确定要删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let params = {
          id: this.tasksId
        }
        return new Promise((resolve, reject) => {
          Administration.taskdelete(this, params).then(res => {
            this.$message.success('删除成功！');
            this.onCancel(true);
          }).catch(e => {
            reject(e);
          });
        });
      })
    },
    onCancel (isSuccess) {
      if (this.observer != null) {
        this.observer.cancel(isSuccess);
      }
    }
  }
}
</script>

<style scoped>
h4{margin-bottom: 0;}
.table_container{margin: 10px 0;}
.form-single-info{display: flex;justify-content: center;}
.el-form-info{box-shadow: 0 0 10px rgba(0,0,0,0.05);padding: 20px;}
.el-form-info strong{margin: 0 10px;}
</style>
